/** =====================================================
 * Copyright © hk. 2022-2025. All rights reserved.
 * File name  : 01_sem_demo.c
 * Author     : 上上签
 * Date       : 2023-12-05
 * Version    : 
 * Description: 
 * ======================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <aos/kernel.h>
#include "aos/init.h"
#include "board.h"
#include <k_api.h>
#include "aos/hal/gpio.h"
#include "ulog/ulog.h"

#define RED_LED   0 // PA14
#define GRE_LED   1 // PA15

#define KEY1_PORT 8 // PA5
#define KEY2_PORT 2 // PA22
#define KEY3_PORT 4 // PA23

#define TASK_KEY_NAME "task_key"
#define TASK_LED_NAME "task_led"
#define MOUDLE_NAME   "key_led_sem"

aos_sem_t   key_led_sem;
gpio_dev_t  led_gpio_dev[2] = {0};
gpio_dev_t  key_gpio_dev;
uint32_t    key_value;

void task_key_entry(void *arg)
{
  while(1) {
        hal_gpio_input_get(&key_gpio_dev, &key_value);
        if(!key_value)
        {
            //延时去抖动
           aos_msleep(10);
           //再次判断是否按下
           hal_gpio_input_get(&key_gpio_dev, &key_value);
           if(!key_value)
           {
                printf("key is down signal \r\n");
                aos_sem_signal(&key_led_sem);
                //等待按键松开
                do{
                    hal_gpio_input_get(&key_gpio_dev, &key_value);
                    aos_msleep(10);
                }while(!key_value);
           }

        }
        //10ms 读取一次按键状态
        aos_msleep(10);
    }

}

void task_led_entry(void *arg)
{

    int ret;
    while(1)
    {
        ret = aos_sem_wait(&key_led_sem, AOS_WAIT_FOREVER);
        printf("led is toggle \r\n");
        hal_gpio_output_toggle(&led_gpio_dev[0]);
    }

}
int led_init(void)
{
    //由于PA14时rtl8710的jtag接口，我要使用GPIO功能，必须先关闭jtag借口
    sys_jtag_off();
    led_gpio_dev[0].port = RED_LED;
    led_gpio_dev[0].config = OUTPUT_PUSH_PULL;
    led_gpio_dev[0].priv = NULL;
    //gpio PA14初始化
    hal_gpio_init(&led_gpio_dev[0]);

    led_gpio_dev[1].port = GRE_LED;
    led_gpio_dev[1].config = OUTPUT_PUSH_PULL;
    led_gpio_dev[1].priv = NULL;
    //gpio PA14初始化
    hal_gpio_init(&led_gpio_dev[1]);

    return 0;
}

int application_start(int argc, char *argv[])
{
    int ret;

    led_init();

    key_gpio_dev.port = KEY1_PORT;
    //根据原理图分析配置位输入上拉模式
    key_gpio_dev.config = INPUT_PULL_UP;
    key_gpio_dev.priv = NULL;
    //key 初始化
    hal_gpio_init(&key_gpio_dev);

    aos_set_log_level(AOS_LL_INFO);
    //创建任务
    ret = aos_task_new(TASK_KEY_NAME, task_key_entry, NULL, 4*128);
    if(ret != 0)
    {
        LOGE(MOUDLE_NAME, "task key new error\r\n");
    }
    ret = aos_task_new(TASK_LED_NAME, task_led_entry, NULL, 4*128);
    if(ret != 0)
    {
        LOGE(MOUDLE_NAME, "task led new error\r\n");
    }
    //创建信号量
    aos_sem_new(&key_led_sem,0);

    while(1)
    {
        aos_msleep(1000);
        hal_gpio_output_toggle(&led_gpio_dev[1]);
    }
  
}
